import { EnvironmentalFactorAnalysisParams, ReportParagraphBlock } from "./typings/index";
import { caculateSheetTargtColumnValue, caculateSheetTargtColumnValueMergedByMonth, caculateSheetTargtColumnValueMonth, generateWordParagraBlockByPlainText, generateWordParagraBlockByTableGenerateResult, getAvgSheetDataByMonth, getSheetUniquenTargetValueList } from "./utils";


const genereateTagetKeyReportPararaph = (
    reportParagraphBlockList: ReportParagraphBlock[],
    year: string,
    tagetKeyConfig: TargetKeyConfig,
    targetConfigIndex: number,
    originSheetData: any[]
) => {
    if (originSheetData && originSheetData.length) {
        const {
            name,
            targetKey,
            unit
        } = tagetKeyConfig;
        //开始空气环境监测分析
        //（1）环境温度
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(`（${targetConfigIndex + 1}）${name}`, 'normalParagraph'));
        let ambientTemperatureText = `所有监测站点的${year}年平均${name}${caculateSheetTargtColumnValue(originSheetData, targetKey, 'avg')}${unit}，最高${name}${caculateSheetTargtColumnValue(originSheetData, targetKey, 'max')}${unit}，最低${name}${caculateSheetTargtColumnValue(originSheetData, targetKey, 'min')}${unit}。`;
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(ambientTemperatureText, 'normalParagraph'))
        // 年度环境温度监测概况表
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(`${year}年度${name}监测概况表`, 'smallTableName'));
        const stationNameList: string[] = getSheetUniquenTargetValueList(originSheetData, '站点名称');
        let annualEnvironmentalEemperatureMonitoringTableData = [
            ["监测站点", `${name}${unit}`, "", ""],
            ["监测站点", "最大", "最小", "平均"],
        ]
        const sheetAvaValueByMonthData = getAvgSheetDataByMonth(originSheetData, targetKey);
        const caculateSheetTargtColumnValueMonthMinResult1 = caculateSheetTargtColumnValueMonth(sheetAvaValueByMonthData, '平均值', 'min');
        const caculateSheetTargtColumnValueMonthMaxResult1 = caculateSheetTargtColumnValueMonth(sheetAvaValueByMonthData, '平均值', 'max');
        console.log("sheetAvaValueByMonthData-->", sheetAvaValueByMonthData)
        console.log("caculateSheetTargtColumnValueMonthMinResult1---->", caculateSheetTargtColumnValueMonthMinResult1);
        console.log("caculateSheetTargtColumnValueMonthMaxResult1---->", caculateSheetTargtColumnValueMonthMaxResult1);
        //
        const caculateSheetTargtColumnValueMonthMinResult2 = caculateSheetTargtColumnValueMonth(originSheetData, targetKey, 'min');
        const caculateSheetTargtColumnValueMonthMaxResult2 = caculateSheetTargtColumnValueMonth(originSheetData, targetKey, 'max');
        console.log("caculateSheetTargtColumnValueMonthMinResult2--->", caculateSheetTargtColumnValueMonthMinResult2)
        console.log("caculateSheetTargtColumnValueMonthMaxResult2--->", caculateSheetTargtColumnValueMonthMaxResult2)
        let environmentalEemperatureMonitoringText1 = `${year}年环境监测数据显示：各监测站点中平均${name}最低月份为${caculateSheetTargtColumnValueMonthMinResult1.month}，平均${name}为${caculateSheetTargtColumnValueMonthMinResult1.value}${unit}，站点为${caculateSheetTargtColumnValueMonthMinResult1.name}，平均${name}最高月份${caculateSheetTargtColumnValueMonthMaxResult1.month}，平均${name}${caculateSheetTargtColumnValueMonthMaxResult1.value}${unit}，站点为${caculateSheetTargtColumnValueMonthMaxResult1.name}。`;
        let environmentalEemperatureMonitoringText2 = `所有监测站点中最高${name}所处月份为${caculateSheetTargtColumnValueMonthMaxResult2.month}，${name}为${caculateSheetTargtColumnValueMonthMaxResult2.value}${unit}，站点为${caculateSheetTargtColumnValueMonthMaxResult2.name}；最低${name}所处月份为${caculateSheetTargtColumnValueMonthMinResult2.month}，${name}为${caculateSheetTargtColumnValueMonthMinResult2.value}${unit}，站点为${caculateSheetTargtColumnValueMonthMinResult2.name}。`
        stationNameList.forEach(stationName => {
            console.log("stationName---->", stationName)
            const tempSheetData = originSheetData.filter(row => {
                //@ts-ignore
                return row['站点名称'] == stationName;
            })
            // console.log("tempSheetData--->", tempSheetData);
            const stationMaxValue = caculateSheetTargtColumnValue(tempSheetData, targetKey, 'max');
            const stationMinValue = caculateSheetTargtColumnValue(tempSheetData, targetKey, 'min');
            const stationAvgValue = caculateSheetTargtColumnValue(tempSheetData, targetKey, 'avg');
            annualEnvironmentalEemperatureMonitoringTableData.push([
                stationName,
                stationMaxValue + '',
                stationMinValue + '',
                stationAvgValue + '',
            ])
        })
        reportParagraphBlockList.push(generateWordParagraBlockByTableGenerateResult({
            tableStyle: 'normalTable',
            tableData: annualEnvironmentalEemperatureMonitoringTableData,
            tableColSpanInfoList: [
                {
                    colIndex: 1,
                    rowIndex: 0,
                    colSpan: 3,
                },
            ],
            tableRowSpanInfoList: [
                {
                    rowIndex: 0,
                    colIndex: 0,
                    rowSpan: 2,
                }
            ]
        }))
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(environmentalEemperatureMonitoringText1, 'normalParagraph'));
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(environmentalEemperatureMonitoringText2, 'normalParagraph'));
        //
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(`监测站点各月平均${name}表(单位：${unit} )`, 'smallTableName'));
        const avgSheetData = caculateSheetTargtColumnValueMergedByMonth(originSheetData,targetKey, 'avg');
        reportParagraphBlockList.push(generateWordParagraBlockByTableGenerateResult({
            tableStyle: 'normalTable',
            tableData: avgSheetData
        }))
        //监测站点各月最高环境温度表(单位：°C )
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(`监测站点各月最高${name}表(单位：${unit} )`, 'smallTableName'));
        const maxSheetData = caculateSheetTargtColumnValueMergedByMonth(originSheetData, targetKey, 'max');
        reportParagraphBlockList.push(generateWordParagraBlockByTableGenerateResult({
            tableStyle: 'normalTable',
            tableData: maxSheetData
        }))
        // 监测站点各月最低环境温度表(单位：°C )
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText(`监测站点各月最低${name}表(单位：${unit} )`, 'smallTableName'));
        const minSheetData = caculateSheetTargtColumnValueMergedByMonth(originSheetData, targetKey, 'min');
        reportParagraphBlockList.push(generateWordParagraBlockByTableGenerateResult({
            tableStyle: 'normalTable',
            tableData: minSheetData
        }))
    }
}

interface TargetKeyConfig {
    name: string,
    targetKey: string,
    unit: string,
}

interface TypeConfig {
    sheetName: string,
    originSheet: any,
    configList: TargetKeyConfig[]
}

const environmentalFactorAnalysis = (params: EnvironmentalFactorAnalysisParams): ReportParagraphBlock[] => {
    const {
        airMonitoringSheetData,
        waterEnvironmentSheetData,
        soilMonitoringSheetData,
        year
    } = params;
    let reportParagraphBlockList: ReportParagraphBlock[] = [];
    console.log("environmentalFactorAnalysis--->params--->", params)
    try {
        //环境监测报告
        const sheetHeader1 = ["站点名称", "监测时间", "温度（℃）", "降雨量（mm）", "一氧化碳（%）", "臭氧（%）", "二氧化氮（mg/m³）", "二氧化硫（mg/m³）", "大气压（kp）", "负氧离子（个/cm³）", "PM10（Μg/m3）", "PM2.5（Μg/m3）"];
        const sheetHeader2 = ["站点名称", "监测时间", "水温（℃）", "硝态氮（mg/m³）", "PH", "浊度（mg/L）", "溶解氧（%）"];
        const sheetHeader3 = ["站点名称", "监测时间", "土壤PH", "土壤电导率/mS/m", "土壤温度（℃）", "土壤湿度(%)"];
        let typeConfigList: TypeConfig[] = [
            {
                sheetName: "空气环境监测分析",
                originSheet: airMonitoringSheetData,
                configList: [
                    {
                        name: "环境温度",
                        targetKey: '温度（℃）',
                        unit: "°C"
                    },
                    {
                        name: "降雨量",
                        targetKey: '降雨量（mm）',
                        unit: "mm"
                    },
                    {
                        name: "一氧化碳",
                        targetKey: '一氧化碳（%）',
                        unit: "%"
                    },
                    {
                        name: "臭氧",
                        targetKey: '臭氧（%）',
                        unit: "%"
                    },
                    {
                        name: "二氧化氮",
                        targetKey: '二氧化氮（mg/m³）',
                        unit: "mg/m³"
                    },
                    {
                        name: "二氧化硫",
                        targetKey: '二氧化硫（mg/m³）',
                        unit: "mg/m³"
                    },
                    {
                        name: "大气压",
                        targetKey: '大气压（kp）',
                        unit: "kp"
                    },
                    {
                        name: "负氧离子",
                        targetKey: '负氧离子（个/cm³）',
                        unit: "个/cm³"
                    },
                    {
                        name: "PM10",
                        targetKey: 'PM10（Μg/m3）',
                        unit: "Μg/m3"
                    },
                    {
                        name: "PM2.5",
                        targetKey: 'PM2.5（Μg/m3）',
                        unit: "Μg/m3"
                    },
                ]
            },
            {
                sheetName: "水环境监测分析",
                originSheet: waterEnvironmentSheetData,
                configList: [
                    {
                        name: "水温",
                        targetKey: '水温（℃）',
                        unit: "℃"
                    },
                    {
                        name: "硝态氮",
                        targetKey: '硝态氮（mg/m³）',
                        unit: "mg/m³"
                    },
                    {
                        name: "PH",
                        targetKey: 'PH',
                        unit: ""
                    },
                    {
                        name: "浊度",
                        targetKey: '浊度（mg/L）',
                        unit: "mg/L"
                    },
                    {
                        name: "溶解氧",
                        targetKey: '溶解氧（%）',
                        unit: "%"
                    },
                ]
            },
            {
                sheetName: "土壤监测分析",
                originSheet: soilMonitoringSheetData,
                configList: [
                    {
                        name: "土壤PH",
                        targetKey: '土壤PH',
                        unit: ""
                    },
                    {
                        name: "土壤电导率",
                        targetKey: '土壤电导率/mS/m',
                        unit: "/mS/m"
                    },
                    {
                        name: "土壤PH",
                        targetKey: '土壤PH',
                        unit: ""
                    },
                    {
                        name: "土壤温度",
                        targetKey: '土壤温度（℃）',
                        unit: "℃"
                    },
                    {
                        name: "土壤湿度",
                        targetKey: '土壤湿度(%)',
                        unit: "%"
                    },
                ]
            }
        ]
        reportParagraphBlockList.push(generateWordParagraBlockByPlainText('环境监测报告', 'heading1'));
        typeConfigList.forEach((typeConfig, index) => {
            reportParagraphBlockList.push(generateWordParagraBlockByPlainText(`${index + 1} ${typeConfig.sheetName}`, 'heading6'));
            typeConfig.configList.forEach((targetConfig, targetConfigIndex) => {
                genereateTagetKeyReportPararaph(reportParagraphBlockList, year, targetConfig, targetConfigIndex, typeConfig.originSheet)
            })
        })
        
        const formatPMWithSubscript = (text: string) => {
            // 替换PM2.5，使用Unicode下标字符
            let formatted = text.replace(/PM2\.5/g, 'PM₂.₅');
          
            // 替换PM10，使用Unicode下标字符
            formatted = formatted.replace(/PM10/g, 'PM₁₀');
          
            // 替换m3为m³
            formatted = formatted.replace(/m3/g, 'm³');
          
            return formatted;
          }
          
        reportParagraphBlockList.forEach(paragraph => {
            if(paragraph.type == 'Text'){
                //@ts-ignore
                paragraph.text = formatPMWithSubscript(paragraph.text);
            }
        })
        return reportParagraphBlockList;
    } catch (e) {
        console.log("environmentalFactorAnalysis--->err", e)
        return reportParagraphBlockList;
    }
}


export default environmentalFactorAnalysis;




